# -*- coding: utf-8 -*-

"""
游戏逻辑模块
"""

import random
import os
import glob
from src.ai.emotion_engine import EmotionEngine
from src.ai.image_generator import ImageGenerator
from src.ai.difficulty_predictor import DifficultyPredictor
from src.data.database import DatabaseManager
from src.data.config_manager import ConfigManager


class GameLogic:
    def __init__(self):
        """初始化游戏逻辑"""
        self.emotion_engine = EmotionEngine()
        self.image_generator = ImageGenerator()
        self.difficulty_predictor = DifficultyPredictor()
        self.database = DatabaseManager()
        self.config = ConfigManager()
        
        self.current_player_id = None
        self.current_game_id = None
        self.puzzle_image = None
        self.puzzle_pieces = []
        self.game_state = "idle"  # idle, playing, paused, completed
        
    def start_new_game(self, player_name, image_path=None):
        """
        开始新游戏
        
        Args:
            player_name (str): 玩家姓名
            image_path (str, optional): 图片路径，如果为None则生成图像
        """
        # 获取或创建玩家
        self.current_player_id = self.database.add_player(player_name)
        
        # 获取玩家统计数据
        player_stats = self.database.get_player_stats(self.current_player_id)
        
        # 分析情感（如果提供了图片）
        if image_path:
            emotion_data = self.emotion_engine.analyze_image_emotion(image_path)
        else:
            # 生成默认情感数据
            emotion_data = {
                "dominant_emotion": "平静",
                "confidence": 0.8,
                "emotions": {"平静": 0.8, "快乐": 0.1, "忧郁": 0.1}
            }
            
        # 预测难度
        if self.config.get("ai.difficulty_prediction_enabled", True):
            difficulty = self.difficulty_predictor.predict_difficulty(player_stats, emotion_data)
        else:
            difficulty = self.config.get("game.default_difficulty", "中等")
            
        # 生成或加载图像
        if image_path:
            # 实际实现中应该加载指定图片
            pass
        else:
            # 检查是否设置了图片目录
            image_dir = self.config.get("images.puzzle_image_directory", "")
            if image_dir and os.path.exists(image_dir):
                # 从目录中随机选择图片
                image_path = self._get_random_image_from_directory(image_dir)
                if image_path:
                    # 实际实现中应该加载指定图片
                    pass
                else:
                    # 如果目录中没有有效图片，则生成图像
                    theme = self.emotion_engine.suggest_puzzle_theme(emotion_data)
                    self.puzzle_image = self.image_generator.generate_puzzle_image(theme)
            else:
                # 生成图像
                theme = self.emotion_engine.suggest_puzzle_theme(emotion_data)
                self.puzzle_image = self.image_generator.generate_puzzle_image(theme)
            
        # 设置游戏状态
        self.game_state = "playing"
        
        # 保存游戏记录
        self.current_game_id = self.database.save_game_record(
            player_id=self.current_player_id,
            difficulty=difficulty,
            puzzle_size=self.config.get("game.default_puzzle_size", 4),
            time_spent=0,
            moves_count=0,
            completed=False,
            emotion_data=emotion_data
        )
        
        return {
            "difficulty": difficulty,
            "emotion_data": emotion_data,
            "puzzle_image": self.puzzle_image
        }
        
    def _get_random_image_from_directory(self, directory):
        """
        从指定目录中随机获取一张图片
        
        Args:
            directory (str): 图片目录路径
            
        Returns:
            str: 随机选择的图片路径，如果没有找到图片则返回None
        """
        # 支持的图片格式
        image_extensions = ['*.jpg', '*.jpeg', '*.png', '*.bmp', '*.gif']
        image_files = []
        
        # 递归搜索目录中的所有图片文件
        for extension in image_extensions:
            pattern = os.path.join(directory, '**', extension)
            image_files.extend(glob.glob(pattern, recursive=True))
            
        # 如果找到了图片文件，随机选择一个
        if image_files:
            return random.choice(image_files)
            
        return None
        
    def get_player_stats(self, player_id=None):
        """
        获取玩家统计信息
        
        Args:
            player_id (int, optional): 玩家ID，如果为None则使用当前玩家
            
        Returns:
            dict: 玩家统计信息
        """
        if player_id is None:
            player_id = self.current_player_id
            
        if player_id is None:
            return None
            
        return self.database.get_player_stats(player_id)
        
    def save_game_progress(self, time_spent, moves_count, completed=False):
        """
        保存游戏进度
        
        Args:
            time_spent (int): 已用时间(秒)
            moves_count (int): 移动步数
            completed (bool): 是否完成游戏
        """
        if self.current_game_id is None:
            return
            
        # 这里应该更新游戏记录，实际实现中需要更复杂的逻辑
        pass
        
    def get_game_settings(self):
        """获取游戏设置"""
        return {
            "difficulty": self.config.get("game.default_difficulty", "中等"),
            "puzzle_size": self.config.get("game.default_puzzle_size", 4),
            "enable_sound": self.config.get("game.enable_sound", True),
            "enable_music": self.config.get("game.enable_music", True),
            "puzzle_image_directory": self.config.get("images.puzzle_image_directory", "")
        }
        
    def update_game_setting(self, key, value):
        """
        更新游戏设置
        
        Args:
            key (str): 设置键
            value: 设置值
        """
        self.config.set(f"game.{key}", value)
        
    def update_image_directory_setting(self, directory_path):
        """
        更新图片目录设置
        
        Args:
            directory_path (str): 图片目录路径
        """
        self.config.set("images.puzzle_image_directory", directory_path)